<?php

namespace app\index\controller;

use app\common\model\ChatRecord;
use GatewayClient\Gateway;
use Text2pic\Transform;
use think\Controller;

class Index extends Controller
{
	public function index()
	{
		/*$transform = new Transform('根据热门自动发布到微博，并不一定代表本平台观点。关注i沈工可匿名发布。',env('root_path').'public/uploads/water_img',url('/',[],true,true).'uploads/water_img',env('root_path').'public/static/font.TTF');
		$result = $transform->generate("",'某同学');
		echo "<img src='".$result['data']['url']."'>";*/
		$mt_id = time() . mt_rand(100000, 999999);
		return $this->fetch('', [ 'mt_id' => $mt_id ]);
	}
	
	public function register()
	{
		$uid       = input('mt_id');
		$client_id = input('client_id');
		Gateway::bindUid($client_id, $uid);
		return $this->success('绑定成功');
	}
	
	public function login_success($mt_id)
	{
//		$mt_id = input('mt_id');
		$userinfo = [ 'id' => 2, 'username' => 'tegic' ];
		cache('userinfo:' . $mt_id, $userinfo, 60 * 5);
		Gateway::sendToUid($mt_id, json_encode([
			'type'  => 'success',
			'cache' => '124'
		]));
		echo 'success';
	}
	
	public function check()
	{
		$mt_id = input('mt_id');
		$data  = cache('userinfo:' . $mt_id);
		if (!$data) {
			$this->error('二维码过期');
		}
		$this->success($data);
	}
	
	public function chat()
	{
		$fromid = input('fromid', 1);
		$toid   = input('toid', 2);
		cache('chatToId:' . $fromid, $toid);
		$map1 = [
			[ 'fromid', 'eq', $fromid ],
			[ 'toid', 'eq', $toid ],
		];
		
		$map2        = [
			[ 'fromid', 'eq', $toid ],
			[ 'toid', 'eq', $fromid ],
		];
		$count       = ( new ChatRecord() )->whereOr([ $map1, $map2 ])->count('id');
		$chat_record = ( new ChatRecord() )->whereOr([ $map1, $map2 ])->order('id')->limit(( $count - 10 <= 0 ) ? 0 : $count - 10, 10)->select();
		$this->assign('data', $chat_record);
		return $this->fetch('chat', [ 'fromid' => $fromid, 'toid' => $toid ]);
	}
}
